import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store"
// import Home from "../views/Home"
// import Login from "../views/Login"
// import Serch from "../views/Serch"
// import Register from "../views/Register"


Vue.use(VueRouter)

const routes = [
  
  {
    path: '/',
    name: 'Home',
    component: () => import( '../views/Home')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login')
  },
  {
    // path:'/serch',
    path: '/serch/:keyword?',
    name: 'Serch',
    component: () => import('@/views/Serch')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register')
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import('@/views/Detail')
  },
  {
    path: '/addcartsuccess',
    name: 'AddCartSuccess',
    component: () => import('@/views/AddCartSuccess')
  },
  {
    path: '/shopcart',
    name: 'ShopCart',
    component: () => import('@/views/ShopCart')
  },
  {
    path: '/center',
    name: 'Center',
    component: () => import('@/views/Center')
  },
  {
    path: '/pay',
    name: 'Pay',
    component: () => import('@/views/Pay')
  },
  {
    path: '/paysuccess',
    name: 'PaySuccess',
    component: () => import('@/views/PaySuccess')
  },
  {
    path: '/trade',
    name: 'Trade',
    component: () => import('@/views/Trade')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior () { //切换路由后，回到顶页
    return { x: 0, y: 0 }
  },
  routes,
})

//不用登录就能访问的路由
const whiteList = [
  "Home","Login","Register","Search","Detail","ShopCart","AddCartSuccess"
]
//定义路由全局导航守卫
router.beforeEach((to,from ,next)=>{
  //在白名单，或者有token
  if( whiteList.includes(to.name) || store.state.login.token ){
    next()
    return
  }
  //否则就跳到登录页
  // next("`/login?redirect=${to.path}`")

  next({
    name:"Login",
    query:{
      redirect:to.path
    }
  })
})
export default router
